package tichu_project252.Controller;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JButton;
import tichu_project252.Model.Model;
import tichu_project252.View.GameFrame;
import tichu_project252.View.Player.PlayerPanel;
import tichu_project252.View.Player.playBomb;

/**
 * Handles the Play Bomb button.
 *
 * <p> <b> Invariants: </b> </p>
 *
 * @author Alexandra Barka, ΑΜ: 2867, login : barka.
 * @author Euaggelia Petauraki AM: 2875 login: petavraki.
 * @version %I%, %G%
 *
 */
public class playBombHandler extends Controller implements ActionListener {

    /**
     * The playBombHandler defines the behavior of the "Play Bomb" buttons when
     * an action is performed on them.
     *
     * <p><b>Constructor: </b> playBombHandler(Model m)</p>
     *
     * <p><b>Precondition: </b> There is a model </p> <p><b>Postcondition: </b>
     * constructs a valid controller </p>
     *
     * @see <a
     * href="http://docs.oracle.com/javase/tutorial/java/IandI/super.html">super</a>
     *
     */
    public playBombHandler(Model m, int n) {
        super(m);


    }

    /**
     * Invoked when an action occurs.
     *
     * <p><b>Precondition: </b> The button is pushed </p> <p><b>Postcondition:
     * </b> The method handleBomb is performed. </p>
     *
     * @see ActionListener
     */
    @Override
    public void actionPerformed(ActionEvent e) {


        JButton temp = (JButton) e.getSource();
        PlayerPanel p = (PlayerPanel) temp.getParent().getParent(); //find the player Panel 

        int player = ((playBomb) temp).getPlayer();
        GameFrame g = (GameFrame) temp.getParent().getParent().getParent().getParent().getParent().getParent().getParent(); //find the gameframe


        if ((m.getPlayer(player).hasBomb() || m.getPlayer(player).hasStreetBomb()) && m.getTable().getLastDropped().size() != 0 //if player has bomb & the table hasnt got cards in it and the Hund card isnt in the table 
                && !"Hund".equals(m.getTable().getLastDropped().get(0).getstringRepr())) {
            if (m.handleBomb(player)) { // the player can play bomb
                p.cleanup();
                p.invalidate();
                p.validate();
                try {
                    g.addtoCenter(m.getTable().getLastDropped()); // add it in center
                } catch (IOException ex) {
                    Logger.getLogger(playBombHandler.class.getName()).log(Level.SEVERE, null, ex);
                }
                //if (m.checkScore()) {
                    g.setScore();
                //}
            }
        }
        g.enablePlayer(m.getCurrent());
    }
}
